package com.yssoft.controller.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.yssoft.entity.core.*;
import com.yssoft.entity.special.*;
import com.yssoft.entity.supplier.CirculationInfo;
import com.yssoft.entity.supplier.ProductionBatch;
import com.yssoft.service.core.*;
import com.yssoft.service.sales.TcCompanyModifyService;
import com.yssoft.service.special.*;
import com.yssoft.service.supervise.TraceabilityQueryService;
import org.apache.xmlbeans.impl.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.yssoft.controller.BaseController;
import com.yssoft.utils.UploadFile;
import com.yssoft.utils.UserHelper;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;

/**
 * @author 戈超
 * @time 2018/4/25 下午 02:48
 * @ 企业管理控制器
 */
@Controller
@RequestMapping(value = "/enterprise")
public class EnterpriseController extends BaseController {

    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private AreaService areaService;
    @Resource
    private IndustryCategoryService industryCategoryService;
    @Resource
    private ProductClassifyService productClassifyService;
    @Resource
    private CodeService codeService;
    @Resource
    private DdDetailService ddDetailService;
    @Resource
    private TraceabilityQueryService traceabilityQueryService;

    @Resource
    private TsThreeYearsSalesService tsThreeYearsSalesService;

    @Resource
    private TSCertificationInfoService tSCertificationInfoService;

    @Resource
    private TSFoodSafetyDisposalService tSFoodSafetyDisposalService;

    @Resource
    private TSMediaExposureService tSMediaExposureService;

    @Resource
    private TsPersonnelService tsPersonnelService;

    @Resource
    private TsQualificationProofService tsQualificationProofService;

    @Resource
    private TsSuspensionResumptionService tsSuspensionResumptionService;
    @Resource
    private TcCompanyModifyService modifyService;
    @Autowired
    private CompanyServe companyServe;
    @Value("${fast_url}")
    private String fastUrl;

    @Value("${local_path}")
    private String localPath;

    /**
     * 跳转到企业信息页面
     *
     * @return
     */
    @RequestMapping("/enterprisePage")
    public String toEnterprise(Model model) {
        Integer tEId = UserHelper.getCurrentCompanyId();
        model.addAttribute("tEId", tEId);
        Integer isSystem = enterpriseService.queryRoleIdByAccId();
        model.addAttribute("isSystem", isSystem);
    	/*String permissions = enterpriseService.queryRolePermissions();
    	model.addAttribute("permissions", permissions);*/
        return "core/enterprise/enterprise";
    }

    /**
     * 跳转到企业基本信息页面
     *
     * @return
     */
    @RequestMapping("/information")
    public String toInformation(Model model) {
        Integer enterpriseId = UserHelper.getCurrentCompanyId();
        if (enterpriseId != null && !"".equals(enterpriseId)) {
            /*查询企业信息*/
            TEnterprise tenterprise = enterpriseService.queryEnterpriseById(enterpriseId);
            model.addAttribute("tenterprise", tenterprise);
            TcCompany tcCompany = companyServe.queryCompanyInfoByLicense(tenterprise.getSc());
            model.addAttribute("company", tcCompany);
            String idnumberPath = tcCompany.getIdnumberPath();
            System.out.println(idnumberPath);
            model.addAttribute("fastUrl", fastUrl);
            /*查询区域信息*/
            TArea area = areaService.queryAreaById(tenterprise.getT_a_id());
            if (area != null) {
                model.addAttribute("areaname", area.getName());
            }
            /*查询行业类别*/
            TIndustryCategory industry = industryCategoryService.queryRoleById(tenterprise.getT_i_id());
            if (industry != null) {
                model.addAttribute("industryname", industry.getName());
            }
            /*查询生产范围*/
            Map<String, Object> procal = productClassifyService.queryProductByEntId(tenterprise.getId());
            if (procal != null) {
                model.addAttribute("proclaname", procal.get("title"));
                model.addAttribute("proclaId", procal.get("value"));
            }
            /*企业证照信息1-生产许可证*/
            TEnterpriseLicence licence1 = enterpriseService.queryLicenceByCode(enterpriseId, "1");
            model.addAttribute("licence1", licence1);
            /*企业证照信息2-营业执照*/
            TEnterpriseLicence licence2 = enterpriseService.queryLicenceByCode(enterpriseId, "2");
            model.addAttribute("licence2", licence2);
        }
        /*经济性质*/
        Map<String, Object> entTypeparams = new HashMap<String, Object>();
        entTypeparams.put("classify", "entType");
        List<TCode> entType = codeService.findCodeByParam(entTypeparams);
        model.addAttribute("entType", entType);
        /*生产状态*/
        Map<String, Object> produceTypeparams = new HashMap<String, Object>();
        produceTypeparams.put("classify", "produceType");
        List<TCode> produceType = codeService.findCodeByParam(produceTypeparams);
        model.addAttribute("produceType", produceType);

        long id = Long.parseLong(enterpriseId.toString());


        TsThreeYearsSalesEntity tsThreeYearsSalesEntity = new TsThreeYearsSalesEntity();
        tsThreeYearsSalesEntity.setCompanyId(id);
        //查询主体变更记录
        List<TcCompanyModify> tcCompanyModifies = modifyService.queryCompanyModifyList(enterpriseId);
        model.addAttribute("companyModifies", tcCompanyModifies);

        List<TsThreeYearsSalesEntity> salesList = tsThreeYearsSalesService.findList(tsThreeYearsSalesEntity);
        model.addAttribute("salesList", salesList);

        List<TSCertificationInfo> certificationInfoList = tSCertificationInfoService.getAll(0, 10000, id);
        model.addAttribute("certificationInfoList", certificationInfoList);

        List<TSMediaExposureEntity> exposureList = tSMediaExposureService.getAllByPage(0, 10000, id);
        model.addAttribute("exposureList", exposureList);

        TsPersonnelEntity tsPersonnelEntity = new TsPersonnelEntity();
        tsPersonnelEntity.setCompanyId(id);
        List<TsPersonnelEntity> personnelServiceList1 = tsPersonnelService.findList(tsPersonnelEntity);
        model.addAttribute("personnelServiceList1", personnelServiceList1);

        List<TsPersonnelEntity> personnelServiceList2 = tsPersonnelService.findList(tsPersonnelEntity);
        model.addAttribute("personnelServiceList2", personnelServiceList2);

        TsQualificationProofEntity tsQualificationProofEntity = new TsQualificationProofEntity();
        tsQualificationProofEntity.setCompanyId(id);
        List<TsQualificationProofEntity> qualificationProofList = tsQualificationProofService.findList(tsQualificationProofEntity);
        model.addAttribute("qualificationProofList", qualificationProofList);

        TsSuspensionResumptionEntity tsSuspensionResumptionEntity = new TsSuspensionResumptionEntity();
        tsSuspensionResumptionEntity.setCompanyId(id);
        List<TsSuspensionResumptionEntity> resumptionList = tsSuspensionResumptionService.findList(tsSuspensionResumptionEntity);
        model.addAttribute("resumptionList", resumptionList);

        return "core/information/informationView";
    }

    //新增路由====================================================

    /**
     * 新增近三年销售情况路由
     */
    @RequestMapping("/sales/add/{id}")
    public String salesAdd(ModelMap mmap, @PathVariable("id") Long id) {
        mmap.addAttribute("action", "addTsThreeYearsSales");
        mmap.put("companyId", id);
        return "core/information/salesForm";
    }

    /**
     * 新增企业停复产路由 resumptionType
     */
    @RequestMapping("/resumption/add/{id}")
    public String resumptionAdd(ModelMap mmap, @PathVariable("id") Long id) {
        mmap.addAttribute("action", "addResumption");
        /*生产状态*/
        Map<String, Object> resumptionTypeParams = new HashMap<String, Object>();
        resumptionTypeParams.put("classify", "resumptionType");
        List<TCode> resumptionType = codeService.findCodeByParam(resumptionTypeParams);
        mmap.addAttribute("resumptionType", resumptionType);

        mmap.put("companyId", id);
        return "core/information/resumptionForm";
    }

    /**
     * 新增资质证明路由
     */
    @RequestMapping("/proof/add/{id}")
    public String proofAdd(ModelMap mmap, @PathVariable("id") Long id) {
        mmap.addAttribute("action", "addProof");
        mmap.put("companyId", id);
        return "core/information/proofForm";
    }

    /**
     * 新增人员信息路由
     */
    @RequestMapping("/personnel/add/{id}")
    public String personnelAdd(ModelMap mmap, @PathVariable("id") Long id) {
        mmap.addAttribute("action", "addPersonnel");
        mmap.put("companyId", id);
        Map<String, Object> resumptionTypeParams = new HashMap<String, Object>();
        resumptionTypeParams.put("classify", "cardType");
        List<TCode> cardType = codeService.findCodeByParam(resumptionTypeParams);
        mmap.addAttribute("cardType", cardType);
        //查询字典
        Map<String, Object> titleParam = new HashMap<>();
        titleParam.put("classify", "titles");
        List<TCode> titles = codeService.findCodeByParam(titleParam);//职称
        Map<String, Object> titleParam2 = new HashMap<>();
        titleParam2.put("classify", "major");
        List<TCode> major = codeService.findCodeByParam(titleParam2);//专业
        Map<String, Object> titleParam3 = new HashMap<>();
        titleParam3.put("classify", "education");
        List<TCode> education = codeService.findCodeByParam(titleParam3);//文化程度
        Map<String, Object> titleParam4 = new HashMap<>();
        titleParam4.put("classify", "duties");
        titleParam4.put("companyId", UserHelper.getCurrentCompanyId());
        List<TDdDetail> job = ddDetailService.findDdDetailByParam(titleParam4);//职务
        mmap.addAttribute("titles", titles);
        mmap.addAttribute("major", major);
        mmap.addAttribute("education", education);
        mmap.addAttribute("job", job);
        return "core/information/personnelForm";
    }

    /**
     * 新增媒体曝光信息表路由
     */
    @RequestMapping("/exposure/add/{id}")
    public String exposureAdd(ModelMap mmap, @PathVariable("id") Long id) {
        mmap.addAttribute("action", "addExposure");
        mmap.put("enterpriseId", id);
        return "core/information/exposureForm";
    }

    /**
     * 新增产品资质信息表路由
     */
    @RequestMapping("/certificationInfo/add/{id}")
    public String certificationInfoAdd(ModelMap mmap, @PathVariable("id") Long id) {
        mmap.addAttribute("action", "addCertificationInfo");
        mmap.put("companyId", id);
        return "core/information/certificationInfoForm";
    }

    //编辑路由==============================================================

    /**
     * 编辑近三年销售情况路由
     */
    @RequestMapping("/sales/edit/{id}")
    public String salesEdit(ModelMap mmap, @PathVariable("id") String id) {
        TsThreeYearsSalesEntity entity = tsThreeYearsSalesService.getById(id);
        mmap.addAttribute("action", "editTsThreeYearsSales");
        mmap.put("entity", entity);
        return "core/information/salesForm";
    }

    /**
     * 编辑企业停复产路由
     */
    @RequestMapping("/resumption/edit/{id}")
    public String resumptionEdit(ModelMap mmap, @PathVariable("id") String id) {
        // 使用自定义的selectById方法，确保字段映射正确
        TsSuspensionResumptionEntity entity = tsSuspensionResumptionService.getBaseMapper().selectById(id);
        mmap.addAttribute("action", "editResumption");
        Map<String, Object> resumptionTypeParams = new HashMap<String, Object>();
        resumptionTypeParams.put("classify", "resumptionType");
        List<TCode> resumptionType = codeService.findCodeByParam(resumptionTypeParams);
        mmap.addAttribute("resumptionType", resumptionType);
        mmap.put("entity", entity);
        // 获取已上传文件的详细信息
        if (entity != null && entity.getReport() != null && !entity.getReport().isEmpty()) {
            Map<String, Object> fileInfo = getFileInfo(entity.getReport(), null);
            mmap.put("fileInfo", fileInfo);
        }

        return "core/information/resumptionForm";
    }

    /**
     * 编辑资质证明路由
     */
    @RequestMapping("/proof/edit/{id}")
    public String proofEdit(ModelMap mmap, @PathVariable("id") String id) {
        try {
            TsQualificationProofEntity entity = tsQualificationProofService.getById(id);
            mmap.addAttribute("action", "editProof");
            mmap.put("entity", entity);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "core/information/proofForm";
    }

    /**
     * 编辑人员信息路由
     */
    @RequestMapping("/personnel/edit/{id}")
    public String personnelEdit(ModelMap mmap, @PathVariable("id") String id) {
        TsPersonnelEntity entity = tsPersonnelService.getById(id);
        mmap.addAttribute("action", "editPersonnel");
        mmap.put("entity", entity);
        Map<String, Object> resumptionTypeParams = new HashMap<String, Object>();
        resumptionTypeParams.put("classify", "cardType");
        List<TCode> cardType = codeService.findCodeByParam(resumptionTypeParams);
        mmap.addAttribute("cardType", cardType);
        //查询字典
        Map<String, Object> titleParam = new HashMap<>();
        titleParam.put("classify", "titles");
        List<TCode> titles = codeService.findCodeByParam(titleParam);//职称
        Map<String, Object> titleParam2 = new HashMap<>();
        titleParam2.put("classify", "major");
        List<TCode> major = codeService.findCodeByParam(titleParam2);//专业
        Map<String, Object> titleParam3 = new HashMap<>();
        titleParam3.put("classify", "education");
        List<TCode> education = codeService.findCodeByParam(titleParam3);//文化程度
        Map<String, Object> titleParam4 = new HashMap<>();
        titleParam4.put("classify", "duties");
        titleParam4.put("companyId", UserHelper.getCurrentCompanyId());
        List<TDdDetail> job = ddDetailService.findDdDetailByParam(titleParam4);//职务
        mmap.addAttribute("titles", titles);
        mmap.addAttribute("major", major);
        mmap.addAttribute("education", education);
        mmap.addAttribute("job", job);
        // 获取已上传文件的详细信息
        if (entity != null && entity.getAppointmentDocument() != null && !entity.getAppointmentDocument().isEmpty()) {
            Map<String, Object> fileInfo = getFileInfo(entity.getAppointmentDocument(), null);
            mmap.put("fileInfo", fileInfo);
        }
        return "core/information/personnelForm";
    }

    /**
     * 编辑媒体曝光信息表路由
     */
    @RequestMapping("/exposure/edit/{id}")
    public String exposureEdit(ModelMap mmap, @PathVariable("id") String id) {
        TSMediaExposureEntity entity = tSMediaExposureService.getById(id);
        mmap.addAttribute("action", "editExposure");
        mmap.put("entity", entity);
        return "core/information/exposureForm";
    }

    /**
     * 编辑产品资质信息表路由
     */
    @RequestMapping("/certificationInfo/edit/{id}")
    public String certificationInfoEdit(ModelMap mmap, @PathVariable("id") String id) {
        TSCertificationInfo entity = tSCertificationInfoService.getById(id);
        mmap.addAttribute("action", "editCertificationInfo");
        mmap.put("entity", entity);

        // 获取已上传文件的详细信息
        if (entity != null && entity.getTypeReport() != null && !entity.getTypeReport().isEmpty()) {
            Map<String, Object> typeReportFileInfo = getFileInfo(entity.getTypeReport(), null);
            mmap.put("typeReportFileInfo", typeReportFileInfo);
        }

        if (entity != null && entity.getBatchReport() != null && !entity.getBatchReport().isEmpty()) {
            Map<String, Object> batchReportFileInfo = getFileInfo(entity.getBatchReport(), null);
            mmap.put("batchReportFileInfo", batchReportFileInfo);
        }

        if (entity != null && entity.getPackagingImg() != null && !entity.getPackagingImg().isEmpty()) {
            Map<String, Object> packagingImgFileInfo = getFileInfo(entity.getPackagingImg(), null);
            mmap.put("packagingImgFileInfo", packagingImgFileInfo);
        }

        return "core/information/certificationInfoForm";
    }

    //新增方法==============================================

    /**
     * 新增近三年销售情况
     */
    @RequestMapping(value = "/addTsThreeYearsSales")
    public String addTsThreeYearsSales(TsThreeYearsSalesEntity entity, RedirectAttributes redirectAttributes) {
        try {
            tsThreeYearsSalesService.addTsThreeYearsSales(entity);
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败!");
            throw new RuntimeException("保存失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 新增企业停复产情况
     */
    @RequestMapping(value = "/addResumption", method = RequestMethod.POST)
    public String addResumption(TsSuspensionResumptionEntity entity, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            // 使用新的文件上传方法，保存原始文件名
            tsSuspensionResumptionService.addTsSuspensionResumption(entity, file);
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败!");
            throw new RuntimeException("保存失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 新增资质证明情况
     */
    @RequestMapping(value = "/addProof")
    public String addProof(TsQualificationProofEntity entity, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            tsQualificationProofService.addTsQualificationProof(entity, file);
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败!");
            throw new RuntimeException("保存失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 新增人员信息情况
     */
    @RequestMapping(value = "/addPersonnel", method = RequestMethod.POST)
    public String addPersonnel(TsPersonnelEntity entity,
                               @RequestParam(value = "certificateFile", required = false) MultipartFile certificateFile,
                               @RequestParam(value = "file", required = false) MultipartFile file,
                               RedirectAttributes redirectAttributes) {
        try {
            tsPersonnelService.addTsPersonnel(entity, certificateFile, file);
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败!");
            throw new RuntimeException("保存失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 新增媒体曝光信息表情况
     */
    @RequestMapping(value = "/addExposure")
    public String addExposure(TSMediaExposureEntity entity, RedirectAttributes redirectAttributes) {
        try {
            tSMediaExposureService.addTSMediaExposure(entity);
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败!");
            throw new RuntimeException("保存失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 新增产品资质信息表情况
     */
    @RequestMapping(value = "/addCertificationInfo", method = RequestMethod.POST)
    public String addCertificationInfo(TSCertificationInfo entity,
                                       @RequestParam(value = "typeReportFile", required = false) MultipartFile typeReportFile,
                                       @RequestParam(value = "batchReportFile", required = false) MultipartFile batchReportFile,
                                       @RequestParam(value = "packagingImgFile", required = false) MultipartFile packagingImgFile,
                                       RedirectAttributes redirectAttributes) {
        try {
            tSCertificationInfoService.addTSCertificationInfo(entity, typeReportFile, batchReportFile, packagingImgFile);
            redirectAttributes.addFlashAttribute("message", "保存成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "保存失败!");
            throw new RuntimeException("保存失败!请联系开发人员");
        }
        return "redirect:information";
    }


//编辑方法==============================================

    /**
     * 编辑近三年销售情况
     */
    @RequestMapping(value = "/editTsThreeYearsSales")
    public String editTsThreeYearsSales(TsThreeYearsSalesEntity entity, RedirectAttributes redirectAttributes) {
        try {
            tsThreeYearsSalesService.update(entity);
            redirectAttributes.addFlashAttribute("message", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "修改失败!");
            throw new RuntimeException("修改失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 编辑企业停复产情况
     */
    @RequestMapping(value = "/editResumption")
    public String editResumption(TsSuspensionResumptionEntity entity, @RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            // 如果有新文件上传，处理文
            tsSuspensionResumptionService.update(entity, file);
            redirectAttributes.addFlashAttribute("message", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "修改失败!");
            throw new RuntimeException("修改失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 编辑资质证明情况
     */
    @RequestMapping(value = "/editProof")
    public String editProof(TsQualificationProofEntity entity, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            tsQualificationProofService.update(entity, file);
            redirectAttributes.addFlashAttribute("message", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "修改失败!");
            throw new RuntimeException("修改失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 编辑人员信息情况
     */
    @RequestMapping(value = "/editPersonnel")
    public String editPersonnel(TsPersonnelEntity entity, @RequestParam(value = "certificateFile", required = false) MultipartFile certificateFile,
                                @RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            tsPersonnelService.update(entity, certificateFile, file);
            redirectAttributes.addFlashAttribute("message", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "修改失败!");
            throw new RuntimeException("修改失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 编辑媒体曝光信息表情况
     */
    @RequestMapping(value = "/editExposure")
    public String editExposure(TSMediaExposureEntity entity, RedirectAttributes redirectAttributes) {
        try {
            tSMediaExposureService.update(entity);
            redirectAttributes.addFlashAttribute("message", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "修改失败!");
            throw new RuntimeException("修改失败!请联系开发人员");
        }
        return "redirect:information";
    }

    /**
     * 编辑产品资质信息表情况
     */
    @RequestMapping(value = "/editCertificationInfo", method = RequestMethod.POST)
    public String editCertificationInfo(TSCertificationInfo entity,
                                        @RequestParam(value = "typeReportFile", required = false) MultipartFile typeReportFile,
                                        @RequestParam(value = "batchReportFile", required = false) MultipartFile batchReportFile,
                                        @RequestParam(value = "packagingImgFile", required = false) MultipartFile packagingImgFile,
                                        RedirectAttributes redirectAttributes) {
        try {
            tSCertificationInfoService.update(entity, typeReportFile, batchReportFile, packagingImgFile);
            redirectAttributes.addFlashAttribute("message", "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("message", "修改失败!");
            throw new RuntimeException("修改失败!请联系开发人员");
        }
        return "redirect:information";
    }

    //删除方法====================================================

    /**
     * 删除近三年销售情况
     */
    @ResponseBody
    @RequestMapping(value = "/salesRemove", method = RequestMethod.POST)
    public String salesRemove(String id) {
        TsThreeYearsSalesEntity entity = new TsThreeYearsSalesEntity();
        entity.setId(id);
        boolean result = tsThreeYearsSalesService.delete(entity);
        if (result) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 删除企业停复产情况
     */
    @ResponseBody
    @RequestMapping(value = "/resumptionRemove", method = RequestMethod.POST)
    public String resumptionRemove(String id) {
        TsSuspensionResumptionEntity entity = new TsSuspensionResumptionEntity();
        entity.setId(id);
        boolean result = tsSuspensionResumptionService.delete(entity);
        if (result) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 删除资质证明情况
     */
    @ResponseBody
    @RequestMapping(value = "/proofRemove", method = RequestMethod.POST)
    public String proofRemove(String id) {
        TsQualificationProofEntity entity = new TsQualificationProofEntity();
        entity.setId(id);
        boolean result = tsQualificationProofService.delete(entity);
        if (result) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 删除人员信息情况
     */
    @ResponseBody
    @RequestMapping(value = "/personnelRemove", method = RequestMethod.POST)
    public String personnelRemove(String id) {
        TsPersonnelEntity entity = new TsPersonnelEntity();
        entity.setId(id);
        boolean result = tsPersonnelService.delete(entity);
        if (result) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 删除媒体曝光信息表情况
     */
    @ResponseBody
    @RequestMapping(value = "/exposureRemove", method = RequestMethod.POST)
    public String exposureRemove(String id) {
        TSMediaExposureEntity entity = new TSMediaExposureEntity();
        entity.setId(id);
        boolean result = tSMediaExposureService.delete(entity);
        if (result) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 删除产品资质信息表情况
     */
    @ResponseBody
    @RequestMapping(value = "/certificationInfoRemove", method = RequestMethod.POST)
    public String certificationInfoRemove(String id) {
        TSCertificationInfo entity = new TSCertificationInfo();
        entity.setId(id);
        boolean result = tSCertificationInfoService.delete(entity);
        if (result) {
            return "success";
        } else {
            return "error";
        }
    }


    /**
     * 企业列表查询
     *
     * @param page
     * @param limit
     * @param name
     * @param abbreviation
     * @param legalPerson
     * @param contact
     * @param productStat
     * @param approvalStat
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryEnterpriseList")
    public JSONObject queryEnterpriseList(@RequestParam(name = "page", defaultValue = "0") int page,
                                          @RequestParam(name = "limit", defaultValue = "10") int limit, String name, String abbreviation,
                                          String legalPerson, String contact, String productStat, String approvalStat) {
        JSONObject pageList = enterpriseService.queryEnterprisePage(page, limit, name, abbreviation, legalPerson, contact, productStat, approvalStat);
        return pageList;
    }

    /**
     * 跳转企业新增修改界面F
     *
     * @param model
     * @param enterpriseId
     * @return
     */
    @RequestMapping("/enterpriseEdit")
    public String enterpriseEdit(Model model, Integer enterpriseId) {
        try {

            if (enterpriseId != null) {
                /*查询企业信息*/
                TEnterprise tenterprise = enterpriseService.queryEnterpriseById(enterpriseId);
                model.addAttribute("tenterprise", tenterprise);
                /*查询区域信息*/
                TArea area = areaService.queryAreaById(tenterprise.getT_a_id());
                if (area != null) {
                    model.addAttribute("areaname", area.getName());
                }
                /*查询行业类别*/
                TIndustryCategory industry = industryCategoryService.queryRoleById(tenterprise.getT_i_id());
                if (industry != null) {
                    model.addAttribute("industryname", industry.getName());
                }
                /*查询生产范围*/
                Map<String, Object> procal = productClassifyService.queryProductByEntId(tenterprise.getId());
                if (procal != null) {
                    model.addAttribute("proclaname", procal.get("title"));
                    model.addAttribute("proclaId", procal.get("value"));
                }
                /*企业证照信息1-生产许可证*/
                TEnterpriseLicence licence1 = enterpriseService.queryLicenceByCode(enterpriseId, "1");
                model.addAttribute("licence1", licence1);
                //获取许可证证照片文件
                if (licence1 !=null && licence1.getLicenceImg() !=null && !licence1.getLicenceImg().isEmpty()){
                    Map<String, Object> fileInfo = getFileInfo(licence1.getLicenceImg(), licence1.getLicenceImgName());
                    model.addAttribute("licenseFileInfo", fileInfo);
                }


                /*企业证照信息2-营业执照*/
                TEnterpriseLicence licence2 = enterpriseService.queryLicenceByCode(enterpriseId, "2");
                model.addAttribute("licence2", licence2);
                //获取许可证证照片文件
                if (licence2 !=null && licence2.getLicenceImg() !=null && !licence2.getLicenceImg().isEmpty()){
                    Map<String, Object> fileInfo = getFileInfo(licence2.getLicenceImg(), licence2.getLicenceImgName());
                    model.addAttribute("businessLicenseFileInfo", fileInfo);
                }


                // 获取已上传文件的详细信息（与 resumptionEdit 保持一致）
                if (tenterprise != null && tenterprise.getChangeMaterials() != null && !tenterprise.getChangeMaterials().isEmpty()) {
                    Map<String, Object> fileInfo = getFileInfo(tenterprise.getChangeMaterials(), tenterprise.getChangeMaterialName());
                    model.addAttribute("fileInfo", fileInfo);
                }
            }
            /*经济性质*/
            Map<String, Object> entTypeparams = new HashMap<String, Object>();
            entTypeparams.put("classify", "entType");
            List<TCode> entType = codeService.findCodeByParam(entTypeparams);
            model.addAttribute("entType", entType);
            /*生产状态*/
            Map<String, Object> produceTypeparams = new HashMap<String, Object>();
            produceTypeparams.put("classify", "produceType");
            List<TCode> produceType = codeService.findCodeByParam(produceTypeparams);
            model.addAttribute("produceType", produceType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "core/enterprise/enterpriseEdit";
    }

    /**
     * @param file
     * @return Map<String, Object>
     * @方法名称: uploadFile
     * @功能描述: 上传图片
     * @作者: 戈超
     * @创建时间: 2018年4月27日 下午4:22:37
     */
    @ResponseBody
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public Map<String, Object> uploadFile(MultipartFile file) {
        Map<String, Object> fileNames = UploadFile.compressUploadedFile(file);
        return fileNames;
    }

    /**
     * 企业信息保存
     *
     * @param tenterprise
     * @return
     */
    @RequestMapping(value = "/saveEnterprise", method = RequestMethod.POST)
    public String saveEnterprise(TEnterprise tenterprise, String proclaId,
                                 @RequestParam(value = "file", required = false) MultipartFile file,
                                 @RequestParam(value = "licenseImgFile", required = false) MultipartFile licenseImgFile,
                                 @RequestParam(value = "businessLicenseImgFile", required = false) MultipartFile businessLicenseImgFile,
                                 HttpServletRequest request) {
        if (tenterprise.getId() != null && !"".equals(tenterprise.getId())) {
            //修改企业信息
            enterpriseService.updateCompany(tenterprise,licenseImgFile,businessLicenseImgFile);
            enterpriseService.editEnterprise(tenterprise, proclaId, file,licenseImgFile,businessLicenseImgFile);
        }
        return "redirect:enterprisePage";
    }

    /**
     * 企业信息查看
     *
     * @param model
     * @param enterpriseId
     * @return
     */
    @RequestMapping("/selectEnterprise")
    public String selectEnterprise(Model model, String enterpriseId) {
        if (enterpriseId != null && !"".equals(enterpriseId)) {
            /*查询企业信息*/
            TEnterprise tenterprise = enterpriseService.queryEnterpriseById(Integer.parseInt(enterpriseId));
            model.addAttribute("tenterprise", tenterprise);
            /*查询区域信息*/
            TArea area = areaService.queryAreaById(tenterprise.getT_a_id());
            if (area != null) {
                model.addAttribute("areaname", area.getName());
            }
            /*查询行业类别*/
            TIndustryCategory industry = industryCategoryService.queryRoleById(tenterprise.getT_i_id());
            if (industry != null) {
                model.addAttribute("industryname", industry.getName());
            }
            /*查询生产范围*/
            Map<String, Object> procal = productClassifyService.queryProductByEntId(tenterprise.getId());
            if (procal != null) {
                model.addAttribute("proclaname", procal.get("title"));
                model.addAttribute("proclaId", procal.get("value"));
            }
            /*企业证照信息1-生产许可证*/
            TEnterpriseLicence licence1 = enterpriseService.queryLicenceByCode(Integer.parseInt(enterpriseId), "1");
            model.addAttribute("licence1", licence1);
            /*企业证照信息2-营业执照*/
            TEnterpriseLicence licence2 = enterpriseService.queryLicenceByCode(Integer.parseInt(enterpriseId), "2");
            model.addAttribute("licence2", licence2);
        }
        /*经济性质*/
        Map<String, Object> entTypeparams = new HashMap<String, Object>();
        entTypeparams.put("classify", "entType");
        List<TCode> entType = codeService.findCodeByParam(entTypeparams);
        model.addAttribute("entType", entType);
        /*生产状态*/
        Map<String, Object> produceTypeparams = new HashMap<String, Object>();
        produceTypeparams.put("classify", "produceType");
        List<TCode> produceType = codeService.findCodeByParam(produceTypeparams);
        model.addAttribute("produceType", produceType);
        return "core/enterprise/enterpriseView";
    }

    /**
     * 企业信息删除
     *
     * @param enterpriseId
     * @return
     */
    @ResponseBody
    @RequestMapping("/delEnterprise")
    public String delEnterprise(String enterpriseId) {
        int result = enterpriseService.delEnterprise(Integer.parseInt(enterpriseId));
        if (result > 0) {
            return "success";
        } else {
            return "error";
        }
    }

    /**
     * 企业信息多条删除
     *
     * @param enterpriseIds
     * @return
     */
    @ResponseBody
    @RequestMapping("/delEnterprises")
    public String delEnterprises(String enterpriseIds) {
        String[] enterpriseIdArray = enterpriseIds.split(",");
        try {
            for (String s : enterpriseIdArray) {
                enterpriseService.delEnterprise(Integer.parseInt(s));
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 查询区域树
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getAreaTree")
    public String getAreaTree() {
        String areaTree = areaService.queryAreaTree();
        return areaTree;
    }

    /**
     * 查询行业类别树
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getIndustryTree")
    public String getIndustryTree() {
        String industryTree = industryCategoryService.queryIndustryTree();
        return industryTree;
    }

    /**
     * 查询生产范围树
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/getProclaTree")
    public String getProclaTree(String ids) {
        String proclaTree = productClassifyService.queryProclaTree(ids);
        System.out.println(proclaTree);
        return proclaTree;
    }

    /**
     * 获取文件信息
     *
     * @param filePath 文件路径（格式：/files/filename 或 原始文件名|/files/filename）
     * @return 文件信息Map
     */
    private Map<String, Object> getFileInfo(String filePath, String fileNames) {
        Map<String, Object> fileInfo = new HashMap<>();

        try {
            String originalFileName = null;
            String serverFilePath = null;
            String fileName = null;

            // 检查是否是新的格式（包含原始文件名）
            if (filePath != null && filePath.contains("|")) {
                String[] parts = filePath.split("\\|", 2);
                if (parts.length == 2) {
                    originalFileName = parts[0];
                    serverFilePath = parts[1];
                }
            } else {
                // 旧格式，直接使用文件路径
                serverFilePath = filePath;
            }

            // 从虚拟路径转换为实际文件路径
            if (serverFilePath != null && serverFilePath.startsWith("/files/")) {
                fileName = serverFilePath.substring("/files/".length());
            } else {
                fileInfo.put("exists", false);
                fileInfo.put("fileName", originalFileName != null ? originalFileName : "文件路径格式错误");
                return fileInfo;
            }

            // 使用注入的本地路径来查找文件
            if (localPath == null || localPath.trim().isEmpty()) {
                // 如果注入失败，尝试从配置文件中读取
                try {
                    Properties props = new Properties();
                    props.load(getClass().getClassLoader().getResourceAsStream("jdbc.properties"));
                    String configLocalPath = props.getProperty("local_path");
                    if (configLocalPath != null && !configLocalPath.trim().isEmpty()) {
                        localPath = configLocalPath.trim();
                    } else {
                        // 如果还是为空，根据操作系统使用默认路径
                        String os = System.getProperty("os.name").toLowerCase();
                        if (os.contains("win")) {
                            localPath = "C:\\Users\\admin\\files\\m_production";
                        } else {
                            localPath = "/home/yskj/files/m_production";
                        }
                        System.out.println("使用默认路径: " + localPath);
                    }
                } catch (Exception e) {
                    // 如果读取配置文件失败，根据操作系统使用默认路径
                    String os = System.getProperty("os.name").toLowerCase();
                    if (os.contains("win")) {
                        localPath = "C:\\Users\\admin\\files\\m_production";
                    } else {
                        localPath = "/home/yskj/files/m_production";
                    }
                    System.out.println("无法读取配置文件中的local_path，使用默认路径: " + localPath);
                }
            }

            // 规范化路径：统一处理路径分隔符
            if (localPath != null) {
                localPath = localPath.replace("\\", File.separator).replace("/", File.separator);
                // 移除末尾的分隔符（如果有）
                if (localPath.endsWith(File.separator)) {
                    localPath = localPath.substring(0, localPath.length() - 1);
                }
            }

            String actualFilePath = localPath + File.separator + fileName;
            System.out.println("[变更材料预览] 文件路径检查: " + actualFilePath);
            System.out.println("[变更材料预览] 文件绝对路径: " + new File(actualFilePath).getAbsolutePath());
            File file = new File(actualFilePath);

            if (file.exists()) {
                // 获取文件大小
                long fileSize = file.length();

                // 获取文件扩展名
                String extension = "";
                int lastDotIndex = fileName.lastIndexOf('.');
                if (lastDotIndex > 0) {
                    extension = fileName.substring(lastDotIndex + 1).toLowerCase();
                }

                // 根据扩展名确定文件类型和图标
                String fileType = "other";
                String iconClass = "fas fa-file";

                if (extension.matches("jpg|jpeg|png|gif|bmp")) {
                    fileType = "image";
                    iconClass = "fas fa-file-image";
                } else if (extension.matches("pdf")) {
                    fileType = "pdf";
                    iconClass = "fas fa-file-pdf";
                } else if (extension.matches("doc|docx")) {
                    fileType = "word";
                    iconClass = "fas fa-file-word";
                } else if (extension.matches("xls|xlsx")) {
                    fileType = "excel";
                    iconClass = "fas fa-file-excel";
                } else if (extension.matches("txt")) {
                    fileType = "text";
                    iconClass = "fas fa-file-alt";
                }

                // 优先使用原始文件名作为显示文件名
                String displayFileName = originalFileName != null ? originalFileName : fileName;

                fileInfo.put("fileName", fileNames != null ? fileNames : displayFileName);
                fileInfo.put("originalFileName", originalFileName);
                fileInfo.put("serverFileName", fileName);
                fileInfo.put("fileSize", fileSize);
                fileInfo.put("fileType", fileType);
                fileInfo.put("iconClass", iconClass);
                fileInfo.put("extension", extension);
                fileInfo.put("exists", true);
            } else {
                fileInfo.put("exists", false);
                // 即使文件不存在，也优先显示原始文件名
                String displayFileName = originalFileName != null ? originalFileName : (fileName != null ? fileName : "文件不存在");
                fileInfo.put("fileName", displayFileName);
                fileInfo.put("originalFileName", originalFileName);
                fileInfo.put("serverFileName", fileName);
            }
        } catch (Exception e) {
            fileInfo.put("exists", false);
            fileInfo.put("fileName", "获取文件信息失败: " + e.getMessage());
        }

        return fileInfo;
    }
}
